import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Upload,
  FileText,
  Wand2,
  Download,
  CheckCircle,
  AlertTriangle,
  Loader2,
  FileCode2
} from "lucide-react";
import { UploadFile } from "@/api/integrations";
import mammoth from 'mammoth';
import TurndownService from 'turndown';
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';

const turndownService = new TurndownService();

// 前端Word转Markdown
async function convertWordToMarkdownFrontend(file) {
    if (!file) throw new Error("未提供文件");
    const arrayBuffer = await file.arrayBuffer();
    const result = await mammoth.convertToHtml({ arrayBuffer });
    const markdown = turndownService.turndown(result.value);
    return markdown;
}

// 前端生成Word母版（仅替换占位符）
async function generateWordTemplateFrontend(file) {
    if (!file) throw new Error("未提供文件");
    const arrayBuffer = await file.arrayBuffer();
    
    const zip = new PizZip(arrayBuffer);
    const doc = new Docxtemplater(zip, {
        paragraphLoop: true,
        linebreaks: true,
    });

    // 简单地重新生成文档，不进行变量替换，以验证模板结构
    const out = doc.getZip().generate({
        type: "blob",
        mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    });

    // 创建一个可供下载的URL
    const url = URL.createObjectURL(out);
    return { 
        templateUrl: url, 
        templateFilename: `template_${file.name}`,
        // 确保返回一个可被撤销的URL对象，以便稍后清理
        revoke: () => URL.revokeObjectURL(url) 
    };
}


export default function DocumentImporter({ onTemplateCreated, isUpdatingTemplate, templateName }) {
  const [uploadedFile, setUploadedFile] = useState(null);
  const [isUploading, setIsUploading] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [processingStep, setProcessingStep] = useState('');
  const [progress, setProgress] = useState(0);
  const [results, setResults] = useState(null);
  const [error, setError] = useState(null);
  const [generateMarkdown, setGenerateMarkdown] = useState(true);
  const [generateWord, setGenerateWord] = useState(true);

  // 用于存储生成的blob URL，以便之后可以 revoke
  const [blobUrls, setBlobUrls] = useState([]);

  React.useEffect(() => {
    // 组件卸载时清理生成的 blob URL
    return () => {
      blobUrls.forEach(url => URL.revokeObjectURL(url));
    };
  }, [blobUrls]);

  const handleFileUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    if (!file.name.toLowerCase().endsWith('.docx')) {
      setError('请上传 .docx 格式的Word文档');
      return;
    }

    setUploadedFile(file); // 直接存储文件对象，而不是上传
    setError(null);
  };

  const handleGenerateTemplates = async () => {
    if (!uploadedFile) return;

    if (!generateMarkdown && !generateWord) {
      setError('请至少选择一种要生成的模板类型');
      return;
    }

    setIsProcessing(true);
    setProgress(0);
    setError(null);
    setResults(null);
    // 清理旧的 blob URL
    blobUrls.forEach(url => URL.revokeObjectURL(url));
    setBlobUrls([]);

    try {
      let markdownResult = null;
      let wordTemplateResult = null;
      const newBlobUrls = [];

      const totalSteps = (generateMarkdown ? 1 : 0) + (generateWord ? 1 : 0);
      let currentProgress = 0;
      const progressIncrement = 100 / totalSteps;

      if (generateMarkdown) {
        setProcessingStep('正在生成Markdown模板...');
        setProgress(Math.min(currentProgress + 10, 100));

        try {
          markdownResult = await convertWordToMarkdownFrontend(uploadedFile);
        } catch (error) {
          throw new Error(`Markdown模板生成失败: ${error.message}`);
        }

        currentProgress += progressIncrement;
        setProgress(Math.min(currentProgress, 100));
        setProcessingStep('Markdown模板生成完成');
      }

      if (generateWord) {
        setProcessingStep('正在生成Word母版...');
        setProgress(Math.min(currentProgress + 10, 100));
        
        try {
          wordTemplateResult = await generateWordTemplateFrontend(uploadedFile);
          if (wordTemplateResult.templateUrl) {
            newBlobUrls.push(wordTemplateResult.templateUrl);
          }
        } catch (error) {
          throw new Error(`Word母版生成失败: ${error.message}`);
        }

        currentProgress += progressIncrement;
        setProgress(Math.min(currentProgress, 100));
        setProcessingStep('Word母版生成完成');
      }

      setBlobUrls(newBlobUrls);
      setProcessingStep('所有模板生成完成！');
      setProgress(100);

      // 上传原始文件，用于创建Word母版（如果用户选择创建）
      let uploadedWordTemplateUrl = null;
      if (generateWord) {
          const uploadResult = await UploadFile({ file: uploadedFile });
          uploadedWordTemplateUrl = uploadResult.fileUrl;
      }
      
      setResults({
        markdown: markdownResult,
        wordTemplateUrl: uploadedWordTemplateUrl, // 使用上传后的URL
        wordTemplateFilename: generateWord ? `template_${uploadedFile.name}` : null,
        originalFilename: uploadedFile.name,
        downloadableWordUrl: wordTemplateResult?.templateUrl // 仅用于前端下载
      });

    } catch (error) {
      setError(`生成模板失败: ${error.message}`);
    } finally {
      setIsProcessing(false);
      setProgress(0);
      setProcessingStep('');
    }
  };

  const handleCreateTemplate = async () => {
    if (!results) return;

    const baseName = results.originalFilename.replace(/\.docx$/i, '');

    if (onTemplateCreated) {
        try {
            onTemplateCreated({
                name: isUpdatingTemplate ? undefined : `${baseName}_模板`,
                templateType: isUpdatingTemplate ? undefined : 'constructionScheme',
                description: isUpdatingTemplate ? undefined : `基于 ${results.originalFilename} 自动生成的模板`,
                templateContent: {
                  markdown: results.markdown || ""
                },
                wordTemplateUrl: results.wordTemplateUrl || null,
                wordTemplateFilename: results.wordTemplateFilename || null,
                version: isUpdatingTemplate ? undefined : '1.0'
            });
        } catch(e) {
            setError('创建模板失败: ' + e.message);
        }
    }
  };

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Wand2 className="w-5 h-5 text-blue-600" />
          {isUpdatingTemplate ? `更新模板：${templateName}` : '智能文档导入'}
        </CardTitle>
        <p className="text-sm text-gray-600">
          {isUpdatingTemplate
            ? '上传Word文档来更新现有模板的内容，保持模板的基本信息不变'
            : '上传现有的施工方案Word文档，系统将直接从原文档生成Markdown模板和Word母版文件，确保信息完整性'
          }
        </p>
      </CardHeader>

      <CardContent className="space-y-6">
        {/* 文件上传区域 */}
        <div>
          <Label htmlFor="document-upload">选择Word文档</Label>
          <div className="mt-2">
            <Input
              id="document-upload"
              type="file"
              accept=".docx"
              onChange={handleFileUpload}
              disabled={isUploading || isProcessing}
              className="file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
            />
          </div>
          {isUploading && (
            <p className="text-sm text-gray-500 mt-2 flex items-center gap-2">
              <Loader2 className="w-4 h-4 animate-spin" />
              正在上传文件...
            </p>
          )}
        </div>

        {/* 已上传文件信息 */}
        {uploadedFile && !isProcessing && (
          <Alert>
            <FileText className="h-4 w-4" />
            <AlertDescription>
              <div className="flex flex-col gap-4">
                <div>
                  <span className="font-medium">{uploadedFile.name}</span>
                  <span className="text-gray-500 ml-2">
                    ({(uploadedFile.size / 1024).toFixed(1)} KB)
                  </span>
                </div>
                <div className="space-y-2">
                  <Label>选择要生成的模板类型</Label>
                  <div className="flex items-center space-x-4">
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id="generate-markdown"
                        checked={generateMarkdown}
                        onCheckedChange={setGenerateMarkdown}
                      />
                      <label
                        htmlFor="generate-markdown"
                        className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                      >
                        Markdown模板
                      </label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id="generate-word"
                        checked={generateWord}
                        onCheckedChange={setGenerateWord}
                      />
                      <label
                        htmlFor="generate-word"
                        className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                      >
                        Word母版
                      </label>
                    </div>
                  </div>
                </div>

                <Button
                  onClick={handleGenerateTemplates}
                  className="bg-blue-600 hover:bg-blue-700 w-full"
                  disabled={(!generateMarkdown && !generateWord) || !uploadedFile}
                >
                  <Wand2 className="w-4 h-4 mr-2" />
                  生成所选模板
                </Button>
              </div>
            </AlertDescription>
          </Alert>
        )}

        {/* 处理进度 */}
        {isProcessing && (
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Loader2 className="w-4 h-4 animate-spin text-blue-600" />
              <span className="text-sm font-medium">{processingStep}</span>
            </div>
            <Progress value={progress} className="w-full" />
          </div>
        )}

        {/* 错误信息 */}
        {error && (
          <Alert variant="destructive">
            <AlertTriangle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {/* 生成结果 */}
        {results && (
          <Alert className="border-green-200 bg-green-50">
            <CheckCircle className="h-4 w-4" />
            <AlertDescription>
              <div className="space-y-3">
                <p className="font-medium text-green-800">
                  {isUpdatingTemplate ? '内容更新完成！' : '模板生成完成！'}
                </p>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {results.markdown && (
                    <div className="p-3 bg-white rounded border">
                      <h4 className="font-medium text-sm mb-1 flex items-center gap-2">
                        <FileText className="w-4 h-4 text-blue-600" />
                        Markdown模板
                      </h4>
                      <p className="text-xs text-gray-600 mb-2">
                        包含 {results.markdown.split('\n').length} 行内容
                      </p>
                    </div>
                  )}

                  {results.wordTemplateUrl && (
                    <div className="p-3 bg-white rounded border">
                      <h4 className="font-medium text-sm mb-1 flex items-center gap-2">
                        <FileCode2 className="w-4 h-4 text-purple-600" />
                        Word母版
                      </h4>
                      <p className="text-xs text-gray-600 mb-2 truncate" title={results.wordTemplateFilename}>
                        {results.wordTemplateFilename}
                      </p>
                      {results.downloadableWordUrl &&
                        <Button variant="outline" size="sm" className="w-full" asChild>
                          <a href={results.downloadableWordUrl} download={results.wordTemplateFilename}>
                            <Download className="w-4 h-4 mr-2" />
                            下载预览
                          </a>
                        </Button>
                      }
                    </div>
                  )}
                </div>

                <Button onClick={handleCreateTemplate} className="w-full bg-green-600 hover:bg-green-700">
                  <CheckCircle className="w-4 h-4 mr-2" />
                  {isUpdatingTemplate ? '更新模板内容' : '创建模板并保存'}
                </Button>
              </div>
            </AlertDescription>
          </Alert>
        )}

        <div className="text-xs text-gray-500 space-y-1">
          <p className="font-medium">处理说明：</p>
          <ul className="list-disc list-inside space-y-1 ml-2">
            <li>所有文件处理都在您的浏览器中完成，不会上传到服务器，除非您点击“创建模板并保存”。</li>
            <li>处理速度取决于您的电脑性能和文件大小。</li>
            <li>Markdown模板：智能转换格式并替换变量</li>
            <li>Word母版：保持原格式，替换为变量标签</li>
            {isUpdatingTemplate && <li>更新模式：仅更新内容，保持模板基本信息不变</li>}
          </ul>
        </div>
      </CardContent>
    </Card>
  );
}